package com.hry.chat.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ChatServer {
    private static final Logger logger = LoggerFactory.getLogger(ChatServer.class);

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServerBootstrap serverBootstrap;
    private ChannelFuture channelFuture;

    private static final int port = 8088;



    private static class SingletonChatServer {
        static final ChatServer instance = new ChatServer();
    }
    public static ChatServer getInstance() {
        return SingletonChatServer.instance;
    }

    public ChatServer() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChatNettyInitializer());
    }

    /**
     * 启动netty
     */
    public void start() {
        logger.info("netty启动, 端口：{}", port);
        this.channelFuture = serverBootstrap.bind(port);
    }

    /**
     * 关闭netty
     */
    public void stop() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
